//
//  MainControllerViewController.swift
//  MySinaWeiBo
//
//  Created by zhangfuwei on 15/7/29.
//  Copyright © 2015年 zhangfuwei. All rights reserved.
//

import UIKit

class MainControllerViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        addChildViewControllers()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated )
        
        /// 执行按钮设置
        setUpComposebtn()
        
    }
    
    ///  添加子控制器
    
    func addChildViewControllers() {
        
        addChildViewController(HomeController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(DiscoverController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(UIViewController())
        addChildViewController( MessageController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(ProfileController(), title: "我", imageName: "tabbar_profile")
    }
    
    func addChildViewController(vc:UITableViewController , title :String , imageName : String) {
        
        vc.title = title
                
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    /// mark: 设置添加发送按钮
    func setUpComposebtn() {
    
        let width = view.bounds.width / CGFloat(childViewControllers.count)
        
        let rect = CGRect(x: 0, y: 0, width: width, height: tabBar.frame.height)
        
        ComposeButton.frame = CGRectOffset(rect, width * 2, 0)
   
    }
    
    ///  懒加载发送按钮
    lazy var ComposeButton :UIButton = {
        
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        //  添加监听事件 
        btn.addTarget(self , action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
         self.tabBar.addSubview(btn)
        
        return btn
        
    }()
    
    ///  按钮点击事件
    func btnClick() {
        print("跳转到发送界面")
        
        let v  = UserAccount.userLogin() ? ComposeController():OAuthController()
        let nav = UINavigationController(rootViewController: v)
        presentViewController(nav, animated: true, completion: nil)
        
    }
    
}
